<template>
  <view class="wrap" @click="gotoDetail">
		<view class="item">
			<view v-if="isUserHome && item.titleDate" class="user-home-time">{{item.titleDate}}</view>
			<view v-else-if="!isUserHome" class="header-container" @click.stop="gotoUserCenter(item)">
				<view class="portrait-container">
					<user-portrait :userID="item.userID" :src="item.icon" :type="item.type" />
					<image class="manager-tag" v-if="item.type === 'PGC'" src="@/static/images/manager-tag.png" />
				</view>
				<view class="right-container">
					<!-- <view class="user-name">{{item.userName || ''}}</view> -->
					<user-name :userID="item.userID" :text="item.userName || ''" />
					<view class="time">{{getFormatTime(item.date)}}</view>
				</view>
			</view>
			<view class="title" v-if="item.title">{{item.title}}</view>
			<moreLine v-if="item.type === 'UGC' && item.context" :text="item.context" />
      <view v-if="!isTopic && topicList && topicList.length" :style="{ marginTop: '30rpx' }">
        <TopicItems v-model="topicList" :currentPageTopicID="currentPageTopicID" />
      </view>
			<image-container v-if="item.type === 'PGC'" :showNum="item.type === 'UGC'" :images="[{ picturePath: item.pictureOver }]" :pictureTotal="item.pictureTotal" />
			<image-container v-else-if="item.picture && item.picture.length" :showNum="item.type === 'UGC'" :images="item.picture" />
			<view class="bottom-container">
				<view class="view" v-if="item.ifHide === 'N'">
					<image class="img" src="../../static/images/view.svg" />
					{{getFormatNumber(item.pvtotal, '浏览')}}
				</view>
				<view class="comment" @click.stop="gotoDetail({ isClickComment:true })">
					<image class="img" src="../../static/images/comment.svg" />
					{{getFormatNumber(item.discussTotal, '评论')}}
				</view>
				<view class="like" :class="{ 'selected': option.likeStatus }" @click.stop="handleClickLike(option)">
					<image class="img" :src="option.likeStatus ? '../../static/images/like-selected.svg' : '../../static/images/like-normal.svg'" />
					{{getFormatNumber(option.likeTotal, '点赞')}}
				</view>
				<!-- <view class="time" v-if="isUserHome">
					{{getFormatTime(item.date)}}
				</view> -->
			</view>
		</view>
	</view>
</template>

<script>
/** YYYY-MM-DD HH:mm:ss
 * 	•	时间差：当前时间 - 发布时间
 * 	•	5分钟以内显示为“刚刚”
 * 	•	分钟数6~59显示为“XX分钟前”
 * 	•	分钟数60~1440显示为“XX小时前” 24*60=1440
 * 	•	超过1440分钟显示为年月日，“2021/5/24”
 */
  import { mapState } from 'vuex';
  import actions from '@/store/modules/home/actions';
	import customImage from '@/components/image';
	import moreLine from './more-line';
	import imageContainer from './image/image-container';
	import userPortrait from '@/components/community-item/user-portrait';
	import userName from '@/components/community-item/user-name';
	import TopicItems from '@/components/topic-items';

  const { updateLikeArticle } = actions;
	export default {
		components: {
			customImage,
			userPortrait,
			userName,
			moreLine,
			imageContainer,
			TopicItems
		},
		props: {
			// 是否是个人动态主页
			isUserHome: {
				type: Boolean,
				default: false,
			},
			item: {
				type: Object,
				default: () => {},
			},
			prePageUniqueID: {
				type: [String, Number],
				default: '',
			},
			currentPageTopicID: {
				type: [String, Number],
				default: '',
			},
			// 是否是话题动态、资讯
			isTopic: {
				type: Boolean,
				default: false,
			},
		},
		data() {
			return {
				option: {}
			}
		},
		computed: {
      ...mapState({
        umsMember: state => state.app.umsMember,
			}),
			topicList() { // 状态：0->有效；1->无效
				const list = this.item.topicList ? [this.item.topicList[0] || {}] : [];
				return list.filter(item => item.deleteStatus === 0);
			}
		},
		mounted() {
			setTimeout(() => {
				// this.loading = false;
			}, 2000);
		},
		watch: {
			// item(newItem) {
			// 	this.option = newItem;
			// },
			item: {
				handler(newItem) {
					this.option = newItem;
				},
				immediate: true,
			},
		},
		methods: {
			updateLikeArticle,
			getFormatTime(value) {
				return value && this.$u.timeFrom((new Date(value.replace(/-/g, '/'))).getTime());
			},
			getFormatNumber(value, text) {
				return (!value || value === '-' || value - 0 === 0) ? text : this.$formats.toThousand(value);
			},
			gotoUserCenter(item) {
				const pageCount = getCurrentPages().length;
				const { type, userID } = item;
				const query = encodeURIComponent(JSON.stringify({ type, userID }));
				// console.log('gotoUserCenter', pageCount, query);
				const params = {
					url: '/pages-home/user-center/index?item=' + query,
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						// res.eventChannel.emit('acceptDataFromPrePage', { ...item, userID })
					},
				};
				if (pageCount >= 6) {
					uni.redirectTo(params);
				} else {
					uni.navigateTo(params);
				}
			},
			gotoDetail({ isClickComment }) {
				const { currentPageTopicID, prePageUniqueID, isUserHome, item } = this;
				if (prePageUniqueID + '' === item.uniqueID + '') {
					uni.navigateBack();
					return;
				}
				const pageCount = getCurrentPages().length;
				const prePageUserID = (isUserHome && pageCount < 6) ? item.userID : null;
				const prePageTopicID = pageCount < 6 ? currentPageTopicID : null;
				const { type, userID, uniqueID, isDynamic, isInformation, isRecommend } = item;
				const query = encodeURIComponent(JSON.stringify({
					type, userID, uniqueID, prePageUserID, prePageTopicID,
					isDynamic, isInformation, isRecommend,
					isClickComment,
				}));
				// console.log('gotoDetail', pageCount, query);
				const params = {
					url: '/pages-home/community-detail/index?item=' + query,
					events: {
						// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
						acceptDataFromNextPage: function(data) {
							// console.log('acceptDataFromNextPage', data)
						},
					},
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						// res.eventChannel.emit('acceptDataFromPrePage', { data: { ...item, prePageUserID} })
					},
					fail: res => {
						// console.log('fail', res)
					},
				};
				if (pageCount >= 6) {
					uni.redirectTo(params);
				} else {
					uni.navigateTo(params);
				}
			},
			handleClickLike() {
        if(!this.item.uniqueID) return;
        const { phone } = this.umsMember;
        if (!phone) {
          const that = this;
          uni.navigateTo({
            url: '/pages-user/login/login',
            events: {
              // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
              responseLoginResult: function(data) {
                // console.log('acceptDataFromNextPage', data);
                that.updateLikeToService();
              },
            },
          });
        } else {
          this.updateLikeToService();
        }
      },
      updateLikeToService() {
        const {
          isRecommend,
          isDynamic,
          isInformation,
          uniqueID,
					userID,
					type,
        } = this.option;
        const params = {
					isLikeArticle: true,
				  articleUserID: userID, // 发布文章用户ID
          isRecommend,
          isDynamic,
          isInformation,
          likeStatus: !this.option.likeStatus,
          uniqueID,
          beReplyID: type === 'PGC' ? 'PGC' : userID,
          date: this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        };
        this.updateLike(this.option);
        // console.log('updateLikeToService params', params);
        this.updateLikeArticle(params).then(res => {
          if (res && res.code !== 200) {
            this.updateLike(this.option);
					}
					if (res && res.taskMessage) {
						uni.showToast({
							title: res.taskMessage,
							duration: 2000,
							icon: 'none'
						});
					}
        });
      },
      updateLike(item) {
        item.likeStatus = !item.likeStatus;
        if (item.likeStatus) {
          item.likeTotal += 1;
        } else {
          item.likeTotal -= 1;
        }
      },
		}
	}
</script>

<style scoped lang="less">
.wrap {
	padding: 27rpx 30rpx;
	padding-top: 0;
	.item {
		.user-home-time {
			margin-top: 54rpx;
			font-weight: bold;
			font-family: PingFangSC-Semibold;
			font-size: 40rpx;
			color: #1A1A1A;
			line-height: 40rpx;
		}
		.header-container {
			margin-top: 30rpx;
			display: flex;
			align-items: center;
			.portrait-container {
				position: relative;
				margin-right: 16rpx;
				.img {
					min-width: 80rpx;
					width: 80rpx;
					height: 80rpx;
					border-radius: 40rpx;
					overflow: hidden;
				}
				.manager-tag {
					position: absolute;
					right: 0;
					bottom: 0rpx;
					width: 24rpx;
					height: 24rpx;
				}
			}
			.right-container {
				display: flex;
				flex-direction: column;
				.user-name {
					font-family: PingFangSC-Semibold;
					font-weight: bold;
					font-size: 28rpx;
					color: #1A1A1A;
					line-height: 28rpx;
					text-overflow: ellipsis;
					max-width: calc(100vw - 60rpx - 80rpx - 20rpx);
					white-space: nowrap;
					overflow: hidden;
				}
				.time {
					// margin-top: 8rpx;
					font-family: PingFangSC-Regular;
					font-size: 20rpx;
					color: #999999;
					line-height: 20rpx;
					display: inline-block;
				}
			}
		}
		.title {
			margin-top: 30rpx;
			font-family: PingFangSC-Semibold;
			font-size: 32rpx;
			color: #1A1A1A;
			line-height: 48rpx;
			font-weight: bold;
			//
			max-height: 96rpx;//需要设置高度
			//必须结合的属性，将对象作为弹性伸缩盒对象的子元素的排列仿古式
			display:-webkit-box;
			-webkit-box-orient:vertical;
			text-overflow:ellipsis;
			-webkit-line-clamp:2;//例如超过3行显示省略号
			overflow:hidden;
		}
		.bottom-container {
			margin-top: 30rpx;
			display: flex;
			align-items: center;
			.time {
				flex: 1;
				text-align: right;
				font-family: ArialMT;
				font-size: 24rpx;
				color: #4D4D4D;
				line-height: 24rpx;
			}
			.view, .comment, .like {
				font-family: ArialMT;
				font-size: 24rpx;
				color: #4D4D4D;
				line-height: 24rpx;
				display: flex;
				align-items: center;
				margin-right: 44rpx;
				& >.img {
					width: 40rpx;
					height: 40rpx;
					margin-right: 7rpx;
				}
			}
		}
	}
}
</style>
